import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';

export interface FileItem {
    name: string;
    type: 'file' | 'directory';
    size?: number;
    modifiedTime: Date;
    path: string;
}

interface ListFilesParams {
    path?: string;
    sortBy?: 'name' | 'type' | 'size' | 'modifiedTime';
    sortOrder?: 'asc' | 'desc';
    search?: string;
}

// 获取文件列表
export function useFiles(params: ListFilesParams = {}) {
    return useQuery({
        queryKey: ['files', params],
        queryFn: async () => {
            const searchParams = new URLSearchParams();
            if (params.path) searchParams.set('path', params.path);
            if (params.sortBy) searchParams.set('sortBy', params.sortBy);
            if (params.sortOrder) searchParams.set('sortOrder', params.sortOrder);
            if (params.search) searchParams.set('search', params.search);

            const response = await fetch(`/api/files/list?${searchParams.toString()}`);
            if (!response.ok) {
                throw new Error('Failed to fetch files');
            }
            return response.json();
        },
    });
}

// 删除文件或目录
export function useDeleteFile() {
    const queryClient = useQueryClient();

    return useMutation({
        mutationFn: async ({ path, type }: { path: string; type: 'file' | 'directory' }) => {
            const response = await fetch('/api/files/delete', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ path, type }),
            });

            if (!response.ok) {
                const error = await response.json();
                throw new Error(error.error || 'Failed to delete');
            }

            return response.json();
        },
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ['files'] });
        },
    });
}

// 移动文件或目录
export function useMoveFile() {
    const queryClient = useQueryClient();

    return useMutation({
        mutationFn: async ({
            sourcePath,
            targetPath,
            type
        }: {
            sourcePath: string;
            targetPath: string;
            type: 'file' | 'directory'
        }) => {
            const response = await fetch('/api/files/move', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ sourcePath, targetPath, type }),
            });

            if (!response.ok) {
                const error = await response.json();
                throw new Error(error.error || 'Failed to move');
            }

            return response.json();
        },
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ['files'] });
        },
    });
}

// 创建目录
export function useCreateDirectory() {
    const queryClient = useQueryClient();

    return useMutation({
        mutationFn: async ({ path, name }: { path?: string; name: string }) => {
            const response = await fetch('/api/files/mkdir', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({ path, name }),
            });

            if (!response.ok) {
                const error = await response.json();
                throw new Error(error.error || 'Failed to create directory');
            }

            return response.json();
        },
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ['files'] });
        },
    });
}

// 上传文件
export function useUploadFile() {
    const queryClient = useQueryClient();

    return useMutation({
        mutationFn: async ({
            file,
            path
        }: {
            file: File;
            path?: string
        }) => {
            const formData = new FormData();
            formData.append('file', file);
            if (path) formData.append('path', path);

            const response = await fetch('/api/files/upload', {
                method: 'POST',
                body: formData,
            });

            if (!response.ok) {
                const error = await response.json();
                throw new Error(error.error || 'Failed to upload file');
            }

            return response.json();
        },
        onSuccess: () => {
            queryClient.invalidateQueries({ queryKey: ['files'] });
        },
    });
} 